package cz.cvut.manatee.processManager;

public abstract class Query {
/*	
	static {
		System.load("/usr/local/lib/manatee/libmanatee.so");
	}
*/
	/*
	 * Stav ve kterem se dotaz nachazi (ceka na vyhodnoceni, je vyhodnocovan, obsahuje vysledek)
	 * Promenna je obsluhovana prislusnymi set a get metodami
	 */
	protected QueryState state = QueryState.WAITING;
	
	/*
	 * Obsahuje vysledek provadeni dotazu (po dokonceni metody execute)
	 */
	protected Result result = null;
	
	/*
	 * Metodu, jez definuje potomek, obsahuje samotny vypocet dotazu, vyuziva API manateesrv je ziskani vysledku.
	 * Vysledek je ulozen v textove podobe (zabaleny objektem QueryResult).
	 */
	public abstract void execute(ThreadRunnable thread);
		
	public int compare(Query dotaz) {
		return 0;
	}
	
	/*
	 * Vraci soucasny stav dotazu
	 */
	public final QueryState getState() {
		return this.state;
	}
	
	public final boolean isStateWaiting() {
		return this.state == QueryState.WAITING;
	}
	
	public final boolean isStateExecuting() {
		return this.state == QueryState.EXECUTING;
	}
	
	public final boolean isStateSolved() {
		return this.state == QueryState.SOLVED;
	}
	
	/*
	 * Zmeni stav dotazu, pokud stavy jsou menenyn ve spatnem poradi, potom vraci vyjimku BadStateOrderException
	 */
	protected final void setState(QueryState newstate) throws BadStateOrderException, SetTheSameStateException {
		if (newstate == this.state) throw new SetTheSameStateException();
		
		switch (newstate) {
		case WAITING:
			throw new BadStateOrderException();
			//break;
		case EXECUTING:
			if (this.state != QueryState.WAITING) throw new BadStateOrderException();
			break;
		case SOLVED:
			if (this.state != QueryState.EXECUTING) throw new BadStateOrderException();
			break;
		}
		
		this.state = newstate;
	}
	
	/*
	 * Nastavi stav na "provadeni"
	 */
	public void setExecuting() throws BadStateOrderException, SetTheSameStateException {
		this.setState(QueryState.EXECUTING);
	}
	
	/*
	 * Nastavi stav na "provedeno"
	 */
	public void setSolved() throws BadStateOrderException, SetTheSameStateException {
		this.setState(QueryState.SOLVED);
	}

	/*
	 * Vypisuje svuj obsah
	 */
	public String toString() {
		return "";
	}

	public Result getResult() {
		return this.result;
	}
	
	public void setErrorResult(String error) {
		this.result = new ErrorResult(error);
	}
}
